import axios from "axios";
import store from "@/store";
import router from "@/router";
import { Toast } from "vant";
const instance = axios.create({
  baseURL: "http://toutiao.itheima.net",
  // baseURL: "http://toutiao-app.itheima.net/",
});

export default instance;

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    let token = store.state.tokenObj.token;

    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

//添加响应拦截
instance.interceptors.response.use(
  function (response) {
    return response;
  },
  async function (error) {
    // console.dir('error');
    // console.dir(error);
    if (error.response.status == 401) {
     try{
      let res = await axios({
        url: "http://toutiao.itheima.net/v1_0/authorizations",
        method: "put",
        headers: {
          Authorization: "Bearer " + store.state.tokenObj.refresh_token,
        },
      });

      store.commit("saveToken", {
        token: res.data.data.token,
        refresh_token: store.state.tokenObj.refresh_token,
      });

      return await instance(error.config)

     }catch{
        Toast.fail('登录状态已过期，请重新登录')
        router.push('/login')
     }
    } else {
      return Promise.reject(error);
    }
  }
);

